/** 通过 url 判断是否为 图片链接 */
export function isImageUrl(url: string) {
  const str = url.split('?')[0]!.substring(url.lastIndexOf('.') + 1) || '';
  return ['jpg', 'jpeg', 'png', 'webp', 'svg', 'gif'].includes(str.toLocaleLowerCase());
}

/** 通过 url 判断是否为 图片链接 */
export function isVideoUrl(url: string) {
  const str = url.split('?')[0]!.substring(url.lastIndexOf('.') + 1) || '';
  return ['m4v', 'mov', '3gp', '3g2', 'mp4', 'flv', 'f4v', 'webm', 'wmv', 'avi', 'asf'].includes(str.toLocaleLowerCase());
}

/** 得到 */
export function getAssetsFile(url: string) {
  return new URL(url, import.meta.url).href;
}

/**
 * 将图片file转换为Base64对象
 */
export function fileToBase64(file: File) {
  const apppStore = useAppStore();
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = (e) => {
      const date = new Date().getTime();

      if (file.size > 1024 * 40) {
        // 只有大于40kb才压缩
        const img = new Image();
        img.src = String(e.target?.result || '');
        img.onload = async () => {
          const Base64Url = await compressImg(img, file.type);
          resolve({ id: `id_${date}_${apppStore.getBaseID()}`, img: Base64Url });
        };
        img.onerror = () => {
          reject('加载图片失败,002');
        };
      } else {
        resolve({ id: `id_${date}_${apppStore.getBaseID()}`, img: String(e.target?.result || '') });
      }
    };
    reader.onerror = () => {
      reject('加载图片失败,001');
    };
  });
}

/**
 * 压缩图片
 * @param img - 被压缩的img对象
 * @param imgType - 图片类型
 * @param mx - 触发压缩的图片最大宽度限制
 * @param mh - 触发压缩的图片最大高度限制
 * @param quality - 清晰度 0到1之间
 */
export function compressImg(img: HTMLImageElement, imgType = 'image/jpeg', mx = 720, mh = 1280, quality = 0.8) {
  return new Promise((resolve) => {
    const canvas = document.createElement('canvas');
    const context = canvas.getContext('2d');
    const { width: originWidth, height: originHeight } = img;
    // 最大尺寸限制
    const maxWidth = mx;
    const maxHeight = mh;
    // 目标尺寸
    let targetWidth = originWidth;
    let targetHeight = originHeight;
    if (originWidth > maxWidth || originHeight > maxHeight) {
      if (originWidth / originHeight > 1) {
        // 宽图片
        targetWidth = maxWidth;
        targetHeight = Math.round(maxWidth * (originHeight / originWidth));
      } else {
        // 高图片
        targetHeight = maxHeight;
        targetWidth = Math.round(maxHeight * (originWidth / originHeight));
      }
    }
    canvas.width = targetWidth;
    canvas.height = targetHeight;
    if (context) {
      context.clearRect(0, 0, targetWidth, targetHeight);
      // 图片绘制
      context.drawImage(img, 0, 0, targetWidth, targetHeight);
    }
    const dataURL = canvas.toDataURL(imgType, quality); // 转换图片为dataURL
    // const fun = (blob) => {
    //    resolve(blob);
    // };
    // 转换为bolb对象
    // canvas.toBlob(fun, imgType, 0.7);
    resolve(dataURL);
  });
}

/**
 * 获取视频第一帧
 * @param videoSource - 视频源，可以是URL或Blob
 * @returns - 第一帧的File对象
 */
export function getFirstFrameOfVideo(videoSource: Blob | File | string): Promise<{ firstFrame: File; videoWidth: number; videoHeight: number }> {
  return new Promise((resolve, reject) => {
    let url = ''; // 使用createObjectURL创建的URL

    // 创建视频元素
    const video = document.createElement('video');
    video.setAttribute('playsinline', '');
    video.muted = true;

    // 事件监听：当视频可播放时处理
    video.addEventListener('seeked', () => {
      const canvas = document.createElement('canvas');
      canvas.width = video.videoWidth;
      canvas.height = video.videoHeight;
      const context = canvas.getContext('2d');
      if (context) {
        context.drawImage(video, 0, 0, canvas.width, canvas.height);
        const blobCallback = (blob: Blob | null) => {
          if (blob) {
            // 将 Blob 转换为 File
            const firstFrame = new File([blob], 'frame.jpg', { type: 'image/jpeg' });
            resolve({ firstFrame, videoWidth: video.videoWidth, videoHeight: video.videoHeight });
            url && URL.revokeObjectURL(url); // 使用createObjectURL创建的URL应在不再需要时通过revokeObjectURL释放，以避免内存泄漏。
          } else {
            reject(new Error('获取地一帧失败,BD002'));
          }
        };
        canvas.toBlob(blobCallback, 'image/jpeg', 0.7);
      } else {
        reject(new Error('获取地一帧失败,BD001'));
      }
    });

    // 错误处理
    video.addEventListener('error', () => {
      reject(new Error('获取地一帧失败,BD003'));
    });

    // 设置视频源
    if (videoSource instanceof Blob || (videoSource as any) instanceof File) {
      // Blob 或 File
      url = URL.createObjectURL(videoSource as Blob | File);
      video.src = url;
      video.load();
    } else if (typeof videoSource === 'string') {
      video.src = videoSource;
      video.load();
    } else {
      reject(new Error('不支持此类型'));
    }
    video.currentTime = 0.01;
  });
}

/**
 * 得到图片的宽高
 * @param file - 图片,可以是 url 或者File
 */
export function getImageWidthHeight(file: Blob | File | string): Promise<{ width: number; height: number }> {
  return new Promise<{ width: number; height: number }>((resolve, reject) => {
    const img = new Image();
    img.onload = () => {
      const size = { width: img.width, height: img.height };
      resolve(size);
    };
    img.onerror = () => {
      reject(new Error('读取图片失败,BD0001'));
    };

    if (typeof file === 'string') {
      img.src = file;
    } else if (file instanceof File || file instanceof Blob) {
      img.src = URL.createObjectURL(file);
    } else {
      reject(new Error('读取图片失败,BD0002'));
    }
  });
}
